import { useImageProvide, useImageStore } from '@/hooks/image'
import { useRecorderStore } from '@/hooks/recorder'
import { ERecorderBaseStatus, ERecorderStatus, RecordTime } from '@/core/mediaRecorder'
import { EErrorDicKey, RecordError, RecordManage } from '@/core/mediaRecorder/recorder'
import { format } from '@/utils/date'
import Style from './index.module.less'
import { Button, Form, FormItem, Input, message, Modal, Progress } from 'ant-design-vue'
import {
  computed,
  defineComponent,
  onMounted,
  onBeforeUpdate,
  ref,
  getCurrentInstance,
  ComputedRef,
  onUnmounted,
  reactive,
  Ref,
} from 'vue'
import { uploadMedia } from '@/api/record'
import axios from 'axios'

const W8 = 8 * 3600 * 1000
export default defineComponent({
  name: 'MediaRecorderEditor',
  setup() {
    const recortStore = useRecorderStore()
    const activeManage = computed(() => recortStore.state.activeManage)
    const activeManageStatus = ref(ERecorderStatus.none)
    /**验证提交名字 */
    const formModel = reactive({ videoName: '' })
    /**上传百分比*/
    const completePercent = ref(0)
    /**上传状态 */
    const CancelToken = axios.CancelToken
    const source = CancelToken.source()
    /**录制时间 */
    const timeSpan = ref('00:00:00')
    const formRef = ref()
    /** */
    const param: Ref<FormData | undefined> = ref()
    /**computed 无法刷新页面bug */
    const initRecordTime = () => {
      activeManage.value?.initRecordTime({
        start: () => {
          //  imageStore.state.activeManage?.reflashToCanvas();
        },
        every1s: (time: RecordTime, re: RecordManage | undefined) => {
          timeSpan.value = format(new Date(time - W8), 'hh:mm:ss')
        },
        finish: () => {
          stopRecord()
        },
      })
    }
    const reloadfn = (e) => {
      return '重新加载会丢失数据'
    }
    onMounted(() => {
      window.onbeforeunload = reloadfn
      document.addEventListener('visibilitychange', () => {
        if (
          document.hidden &&
          recortStore.state.activeManage?.audioRecorder?.state === ERecorderBaseStatus.recording
        ) {
          pauseRecord()
        }
      })
    })
    onUnmounted(() => {
      window.onbeforeunload = null
    })

    const pauseRecord = () => {
      recortStore.state.activeManage?.pause().catch((e: RecordError) => {
        if (e.code === EErrorDicKey.PauseError) {
          message.error(e.message)
        }
        //  throw new RecordError(EErrorDicKey.Restart);
      })
      activeManageStatus.value = ERecorderStatus.pause
    }

    const stopRecord = () => {
      pauseRecord()
      Modal.confirm({
        title: '保存视频',
        closable: true,
        okText: '上传',
        wrapClassName: 'media-record-toolPage-modal',
        cancelText: '取消',
        content: () => (
          <>
            <Form
              model={formModel}
              ref={(ref: any) => (formRef.value = ref)}
              rules={{
                videoName: [{ required: true, message: '请输入视频名称', trigger: 'blur' }],
              }}
            >
              <FormItem ref="videoName" label={'视频名称'} name="videoName">
                <Input
                  value={formModel.videoName}
                  maxlength={10}
                  onChange={(e) => {
                    formModel.videoName = e.target.value!
                  }}
                ></Input>
              </FormItem>
            </Form>
            {completePercent.value !== 0 ? (
              <Progress percent={completePercent.value}></Progress>
            ) : null}
          </>
        ),
        onOk: async () => {
          const validate = await formRef.value.validate()
          //to do validate
          if (validate) {
            let uploadparam: FormData | undefined
            if (param.value) {
              uploadparam = param.value
            } else {
              uploadparam = await recortStore.state.activeManage?.getUploadParam(
                formModel.videoName,
              )
              param.value = uploadparam
            }
            if (param.value) {
              const res = await uploadMedia(
                uploadparam!,
                (e) => {
                  completePercent.value = ((e.loaded / e.total) * 100) | 0
                },
                source.token,
              )
              if (res?.code === 0) {
                timeSpan.value = '00:00:00'
                activeManageStatus.value = ERecorderStatus.none
                //  that.$forceUpdate();
                message.success('上传成功，视频正在生成中，刷新列表查看链接')
                recortStore.state.mediaStatus = false
              } else {
                completePercent.value = 0
                message.error('上传失败：' + res.msg + ',请重试')
                throw new Error('上传失败：' + res.msg + ',请重试')
              }
            }
          }
        },
        onCancel: () => {
          Modal.confirm({
            title: '取消保存将丢失录制文件',
            okText: () => <span>确认</span>,
            cancelText: () => <span>取消</span>,
            onOk: () => {
              recortStore.state.activeManage?.flyback()
              //*定时器
              recortStore.state.activeManage?.re?.reset()
              activeManageStatus.value = ERecorderStatus.none
              timeSpan.value = '00:00:00'
              Modal.destroyAll()
            },
            onCancel: () => {},
          })
        },
      })
    }
    return () => (
      <div class="w-full bg-white h-14 leading-r2.6 p-2 relative">
        {activeManageStatus.value == ERecorderStatus.none ? (
          <>
            {recortStore.state.mediaCountDownStatus ? (
              <div class={'absolute right-3'}>
                <span class={' text-sm pr-4 text-gray-4D4E58'}>
                  {recortStore.state.startConstDownTime}
                </span>
              </div>
            ) : null}

            <Button
              type={'primary'}
              class={Style['btn_record']}
              onClick={async () => {
                if (!recortStore.state.activeManage?.re) {
                  initRecordTime()
                }
                recortStore.state.activeManage
                  ?.checkAndIniAudio()
                  .then(() => {
                    recortStore.state.mediaCountDownStatus = true
                    recortStore.startConstDownTime(5)
                    setTimeout(async () => {
                      recortStore.state.mediaCountDownStatus = false
                      await recortStore.state.activeManage?.start().catch((e: RecordError) => {
                        recortStore.state.activeManage?.flyback()
                        throw new RecordError(EErrorDicKey.StartError)
                      })
                      activeManageStatus.value = ERecorderStatus.start
                    }, 5000)
                  })
                  .catch((e: RecordError) => {
                    if (e.code === EErrorDicKey.AudioAuthError) {
                      message.error('权限不足，无法录制视频，请点击浏览器链接左侧小锁授予权限')
                    }
                    recortStore.state.activeManage?.flyback()
                    throw new RecordError(EErrorDicKey.AudioAuthError)
                  })

                //that.$forceUpdate();
              }}
            >
              开始录制
            </Button>
          </>
        ) : null}
        {activeManageStatus.value == ERecorderStatus.pause ? (
          <>
            <Button
              class={Style['btn_record']}
              onClick={() => {
                recortStore.state.activeManage?.restart().catch((e: RecordError) => {
                  if (e.code === EErrorDicKey.Restart) {
                    message.error(e.message)
                  }
                  throw new RecordError(EErrorDicKey.Restart)
                })
                activeManageStatus.value = ERecorderStatus.restart
                //that.$forceUpdate();
              }}
            >
              <i class={'iconfont icon-icon_draw_play mr-1 '}></i>
              继续录制
            </Button>
            <div class={'absolute right-3 inline-block'}>
              <span class={' text-sm pr-3 text-gray-4D4E58'}>{timeSpan.value}</span>
              <Button type={'primary'} onClick={stopRecord} class={Style['btn_record']}>
                停止录制
              </Button>
            </div>
          </>
        ) : null}
        {activeManageStatus.value == ERecorderStatus.start ||
        activeManageStatus.value == ERecorderStatus.restart ? (
          <>
            <div class={'absolute right-3'}>
              <span class={' text-sm pr-3 text-gray-4D4E58'}>{timeSpan.value}</span>
              <Button type={'primary'} onClick={stopRecord} class={Style['btn_record']}>
                停止录制
              </Button>
            </div>

            <Button
              class={Style['btn_record']}
              onClick={() => {
                pauseRecord()
              }}
            >
              <i class={'iconfont icon-icon_draw_pause leading-3 mr-1 '}></i>
              暂停录制
            </Button>
          </>
        ) : null}
      </div>
    )
  },
})
